package com.cmos.um.utils;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;

/**
 *
 * @Description: HttpClient
 * @author: zhengchaojie
 * @date 2016年10月19日 下午5:12:37
 *
 */
public class HttpClientUtil {
	private static Logger logger = Logger.getLogger(HttpClientUtil.class);
	private static PoolingHttpClientConnectionManager cm;
	private static String EMPTY_STR = "";
	private static String UTF_8 = "UTF-8";

	private static void init() {
		if (cm == null) {
			cm = new PoolingHttpClientConnectionManager();
			cm.setMaxTotal(50);// 整个连接池最大连接数
			cm.setDefaultMaxPerRoute(5);// 每路由最大连接数，默认值是2
		}
	}

	/**
	 * 通过连接池获取HttpClient
	 *
	 * @return
	 */
	private static CloseableHttpClient getHttpClient() {
		init();
		return HttpClients.custom().setConnectionManager(cm).build();
	}

	/**
	 * @Description: Http Get 带参数
	 * @param url
	 * @param params
	 * @return
	 * @throws URISyntaxException
	 *             String
	 * @Date: 2016年10月19日
	 * @author:zhengchaojie
	 */
	public static String httpGet(String url, Map<String, Object> params) {
		URIBuilder uriBuilder = new URIBuilder();
		uriBuilder.setPath(url);
		ArrayList<NameValuePair> pairs = covertParams2NameValuePairs(params);
		uriBuilder.setParameters(pairs);
		try {
			HttpGet httpGet = new HttpGet(uriBuilder.build());
			return getResult(httpGet);
		} catch (URISyntaxException e) {
			logger.error("Http Get请求" + url + "出错。\n错误日志：" + e.getMessage());
		}
		return EMPTY_STR;
	}

	/**
	 * @Description: http Post 无参数
	 * @param url
	 * @return String
	 * @Date: 2016年10月20日
	 * @author:zhengchaojie
	 */

	public static String httpPost(String url) {
		HttpPost httpPost = new HttpPost(url);
		return getResult(httpPost);
	}

	/**
	 * @Description: Http Post有参数
	 * @param url
	 * @param params
	 * @return
	 * @throws UnsupportedEncodingException
	 *             String
	 * @Date: 2016年10月19日
	 * @author:zhengchaojie
	 */
	public static String httpPost(String url, Map<String, Object> params) {
		HttpPost httpPost = new HttpPost(url);
		ArrayList<NameValuePair> pairs = covertParams2NameValuePairs(params);
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
			return getResult(httpPost);
		} catch (UnsupportedEncodingException e) {
			logger.error("Http Post请求" + url + "出错，参数如下：" + params + "\n错误日志：" + e.getMessage());
		}
		return EMPTY_STR;
	}

	/**
	 * @Description: Http Post Json
	 * @param url
	 * @param json
	 * @return
	 * @throws UnsupportedEncodingException
	 *             String
	 * @Date: 2016年10月19日
	 * @author:zhengchaojie
	 */
	public static String httpPost(String url, JSONObject json) {
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-Type", "application/json");
		try {
			StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");
			//stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");
			httpPost.setEntity(stringEntity);
			String result = getResult(httpPost);
			return result;
		} catch (Exception e) {
			logger.error("Http Post请求" + url + "出错，参数如下：" + json.toString() + "\n错误日志：" + e.getMessage());
		}
		return EMPTY_STR;
	}

	/**
	 * 处理Http请求
	 *
	 * @param request
	 * @return
	 */
	private static String getResult(HttpRequestBase request) {
		CloseableHttpClient httpClient = getHttpClient();
		try {
			CloseableHttpResponse response = httpClient.execute(request);
			System.out.println(response.getStatusLine().getStatusCode());
			if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String result = EntityUtils.toString(entity);
					response.close();
					return result;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return EMPTY_STR;
	}

	/**
	 * @Description: 将参数转成http所需键值对
	 * @param params
	 * @return ArrayList<NameValuePair>
	 * @Date: 2016年10月19日
	 * @author:zhengchaojie
	 */
	private static ArrayList<NameValuePair> covertParams2NameValuePairs(Map<String, Object> params) {
		ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
		for (Map.Entry<String, Object> param : params.entrySet()) {
			pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
		}
		return pairs;
	}

	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			return ip;
		}
		ip = request.getHeader("X-Forwarded-For");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			int index = ip.indexOf(',');
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		} else {
			return request.getRemoteAddr();
		}
	}
}